package com.zlx.xbhy.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zlx.xbhy.entity.User;
import com.zlx.xbhy.mapper.UserMapper;
import com.zlx.xbhy.service.UserService;
import com.zlx.xbhy.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;

/**
 * @Author 周罗校
 * @Description  用户登陆拦截
 * @ClassName LoginInterceptor
 * @date 2020.11.03 15:18:37
 * 该版权归周罗校所有，最终解释权以官方为准
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper mapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        Cookie[] cookies = request.getCookies();
        boolean cookieflag=false;
        if (cookies!=null) {
            if (loginUser!=null){
                //有了session就直接放行
                if (request.getRequestURI().endsWith(request.getContextPath()+"/index.html")){
                    response.sendRedirect(request.getContextPath()+"/html/home.html");
                }
                return true;
            }
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("loginUser".equals(name)) {
                    String value =  URLDecoder.decode(cookie.getValue() , "utf-8");
                    User user = JSONObject.parseObject(value, User.class);
                    List select = mapper.select(user);
                    if (select != null) {//用户存在
                        session.setAttribute("loginUser", user);
                        response.sendRedirect(request.getContextPath()+"/html/home.html");
                        return true;
                    }
                }
            }
        }
        //没有免密登陆
        if (request.getRequestURI().endsWith(request.getContextPath()+"/index.html")){
            return true;
        }else {
        if(loginUser==null){//未登录
            response.sendRedirect(request.getContextPath()+"/index.html");
            return false;
        }
        }
        return true;
    }

}
